/*
 * @Date: 2020-07-15 15:38:06
 * @LastEditTime: 2020-07-15 16:53:41
 * @Description: Dom操作
 * @FilePath: \vue\src\common\utilDom.js
 */ 

import {Type} from 'vue-leng/src/utils/utils'

const hasClass = function(el, className) {
  let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
  return reg.test(el.className)
}

const addClass = function (el, className) {
  if (hasClass(el, className)) {
    return
  }
  let newClass = el.className.split(' ')
  newClass.push(className)
  el.className = newClass.join(' ')
}

const removeClass = function (el, className) {
  if (!hasClass(el, className)) {
    return
  }
  let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g')
  el.className = el.className.replace(reg, ' ')
}

/**
 * @description 获取data-xx
 * @param: import {getData} from '@/common/utilDom'
 * 
 * @param: <div class='isCls' data-xx='selectxx'></div>
 * @param: el:document.querySelector('.isCls')
 * @param: name:xx
 * 
 * @return: selectxx
 * @param: val:newxx
 * @updateDom: <div class='isCls' data-xx='newxx'></div>
 */
const getData = function (el, name, val) {
  let prefix = 'data-'
  if (val) {
    return el.setAttribute(prefix + name, val)
  }
  return el.getAttribute(prefix + name)
}

/**
 * 创建虚拟dom
 * @param ele
 * @param attr
 * @param content
 * @returns {HTMLElement}
 * document.body.appendChild(createDom('small',{className: 'aa'},11))
 * document.body.appendChild(createDom('small',{className: ['item-title']},[createDom('em', {className: 'item-grade'}, `${data.review}分`)]))
 */
const createDom = function (ele, attr = {}, content) {
  const el = document.createElement(ele)
  if ('className' in attr) {
    Type.isArray(attr['className']) ? el.className = attr['className'].join(' ') : el.className = attr['className']
  }
  if ('style' in attr) {
    Object.keys(attr['style']).forEach(key => {
      el.style[key] = attr['style'][key]
    })
  }
  let children = []
  if (content) {
    Type.isArray(content) ? children = children.concat(content) : children.push(content)
    Array.prototype.forEach.call(children.filter(x => x), node => {
      if (Type.isString(node) || Type.isNumber(node)) {
        el.innerHTML = node
      } else {
        el.appendChild(node)
      }
    })
  }
  return el
}

/**
 * 返回元素距离页面顶部的距离
 * @param node
 * @returns {number}
 */
const domOffsetTop = function(node) {
  const dom = document.querySelector(node)
  return dom ? dom.offsetTop + dom.clientHeight : 0
}

export{
  hasClass,
  addClass,
  removeClass,
  getData,
  createDom,
  domOffsetTop
}